﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;

namespace WPFNote.Utilities.CacheHelper.CacheServiceImpl
{
    /// <summary>
    /// .net 内置Cache缓存服务
    /// </summary>
    public class DefaultCache : ICacheService
    {
        private readonly IMemoryCache _cache;

        public DefaultCache(IMemoryCache cache)
        {
            _cache = cache;
        }

        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public bool Save<T>(string key, T value)
        {
            _cache.Set(key, value);
            return true;
        }

        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expire">多少秒后过期</param>
        /// <param name="isSlidingExpiration">是否滑动过期</param>
        public bool Save<T>(string key, T value, int expire, bool isSlidingExpiration = false)
        {
            if (isSlidingExpiration)
            {
                _cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromSeconds(expire),
                });
            }
            else
            {
                _cache.Set(key, value, TimeSpan.FromSeconds(expire));
            }
            return true;
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key">键</param>
        public void Remove(string key)
        {
            _cache.Remove(key);
        }
        /// <summary>
        /// 清空缓存
        /// </summary>
        public void RemoveAll()
        {
            _cache.Dispose();
        }

        /// <summary>
        /// 获取缓存值
        /// </summary>
        /// <typeparam name="T">值类型，class</typeparam>
        /// <param name="key">键</param>
        /// <returns></returns>
        public T Get<T>(string key) where T : class
        {
            var value = _cache.Get<T>(key);
            return value;
        }
    }
}
